// 页面加载完成后执行
window.addEventListener('DOMContentLoaded', function() {
    console.log('页面已加载完成');

    // 移动端菜单切换
    const mobileMenuIcon = document.getElementById('mobileMenuIcon');
    const navLinksContainer = document.getElementById('navLinks');
    
    if (mobileMenuIcon && navLinksContainer) {
        mobileMenuIcon.addEventListener('click', function() {
            navLinksContainer.classList.toggle('active');
            // 切换图标
            if (navLinksContainer.classList.contains('active')) {
                this.textContent = '✕';
            } else {
                this.textContent = '☰';
            }
        });
        
        // 点击导航链接后关闭菜单
        const navLinksItems = navLinksContainer.querySelectorAll('a');
        navLinksItems.forEach(link => {
            link.addEventListener('click', function() {
                if (window.innerWidth <= 768) {
                    navLinksContainer.classList.remove('active');
                    mobileMenuIcon.textContent = '☰';
                }
            });
        });
    }

    // 导航链接交互和平滑滚动
    const navLinks = document.querySelectorAll('.nav-links a');
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (href.startsWith('#')) {
                e.preventDefault();
                const target = document.querySelector(href);
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            }
        });
        
        link.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
            this.style.transition = 'transform 0.3s ease';
        });
        
        link.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });

    // 登录/注册按钮交互
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('login')) {
            window.location.href = '/login';
        } else if (e.target.classList.contains('register')) {
            window.location.href = '/register';
        } else if (e.target.classList.contains('logout-btn')) {
            e.preventDefault();
            logoutUser(e);
        }
    });
    
    // 登出函数
    async function logoutUser(e) {
        try {
            const response = await fetch('/api/logout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            const data = await response.json();
            if (data.success) {
                window.location.reload();
            }
        } catch (error) {
            console.error('登出失败:', error);
            window.location.reload();
        }
    }
    
    // 延迟检查登录状态，确保按钮已经渲染
    setTimeout(() => {
        checkAuthStatus();
    }, 100);
    
    function checkAuthStatus() {
        fetch('/api/check-auth')
            .then(response => response.json())
            .then(data => {
                console.log('检查登录状态:', data);
                if (data.logged_in && data.username) {
                    // 显示已登录状态
                    const loggedInUser = document.getElementById('loggedInUser');
                    const loggedOutButtons = document.getElementById('loggedOutButtons');
                    const usernameDisplay = document.getElementById('usernameDisplay');
                    
                    if (loggedInUser && loggedOutButtons && usernameDisplay) {
                        loggedInUser.style.display = 'flex';
                        loggedOutButtons.style.display = 'none';
                        usernameDisplay.textContent = data.username;
                        console.log('已显示登录用户:', data.username);
                    }
                } else {
                    // 显示未登录状态
                    const loggedInUser = document.getElementById('loggedInUser');
                    const loggedOutButtons = document.getElementById('loggedOutButtons');
                    
                    if (loggedInUser && loggedOutButtons) {
                        loggedInUser.style.display = 'none';
                        loggedOutButtons.style.display = 'flex';
                        console.log('显示未登录状态');
                    }
                }
            })
            .catch(error => {
                console.error('检查登录状态失败:', error);
            });
    }
    
    // 页面加载完成后立即检查
    checkAuthStatus();

    // 开始答题按钮
    const startQuizBtn = document.querySelector('.start-quiz');
    if (startQuizBtn) {
        startQuizBtn.addEventListener('click', function() {
            // 跳转到答题页面
            window.location.href = '/quiz';
        });
    }

    // 浏览题库按钮
    const browseBtn = document.querySelector('.browse-topic');
    if (browseBtn) {
        browseBtn.addEventListener('click', function() {
            const categoriesSection = document.querySelector('.categories');
            if (categoriesSection) {
                categoriesSection.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    }

    // 题库分类卡片点击
    const categoryCards = document.querySelectorAll('.category-card');
    categoryCards.forEach(card => {
        card.addEventListener('click', function() {
            const categoryName = this.querySelector('h3').textContent;
            // 跳转到答题页面，并传递分类参数
            window.location.href = '/quiz?category=' + encodeURIComponent(categoryName);
        });
    });

    // 监听滚动事件，改变导航栏样式
    window.addEventListener('scroll', function() {
        const navbar = document.querySelector('.navBar-t');
        if (window.scrollY > 50) {
            navbar.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.15)';
            navbar.style.background = 'rgba(255, 255, 255, 0.95)';
            navbar.style.backdropFilter = 'blur(10px)';
        } else {
            navbar.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
            navbar.style.background = '#fff';
        }
    });

    // 添加滚动动画
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);

    // 观察所有卡片元素
    document.querySelectorAll('.feature-card, .category-card').forEach(card => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(30px)';
        card.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        observer.observe(card);
    });
});